//
//  NewViewController.m
//  New
//
//  Created by dlios on 15-7-16.
//  Copyright (c) 2015年 yangTao. All rights reserved.
//

#import "NewViewController.h"

@interface NewViewController ()

@end
//#define WITH  self.view.frame.size.width
//#define HEIHT self.view.frame.size.height


@implementation NewViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //打开数据库
    [[NewDataBase sharDataBase]OpenDB];
    //创建列表
    [[NewDataBase sharDataBase]creatTable];
    
    self.scroV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0,WIDTH , 40)];
    self.scroV.contentSize  = CGSizeMake(9 * WIDTH/5,0);

    self.navigationItem.titleView =self.scroV;
    self.scroV.bounces= NO;
    self.scroV.showsHorizontalScrollIndicator =NO;

    self.array = [NSMutableArray arrayWithObjects:@"全球",@"最热",@"美国",@"中国",@"欧洲",@"经济",@"市场",@"央行",@"公司", nil];
    for (int i = 0; i < 9; i++) {
        BaseButton *button = [[BaseButton alloc]initWithFrame:CGRectMake(i * WIDTH/5, 0, WIDTH/5, 40)];
        [button setTitle:[self.array objectAtIndex:i] forState:UIControlStateNormal];
        button.tag = i;
        [self.scroV addSubview:button];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
  
    
    UICollectionViewFlowLayout *collectVFL = [[UICollectionViewFlowLayout alloc]init];
    collectVFL.itemSize = CGSizeMake(WIDTH, HEIGHT );
    collectVFL.minimumInteritemSpacing = 0;
    collectVFL.minimumLineSpacing = 0;
    collectVFL.scrollDirection =UICollectionViewScrollDirectionHorizontal;
    collectVFL.sectionInset = UIEdgeInsetsMake(-115, 0, 0, 0);

    
    self.collectionV = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT ) collectionViewLayout:collectVFL];
   
    self.collectionV.delegate = self;
    self.collectionV.dataSource = self;
    [self.view addSubview:self.collectionV];
    
    
    [self.collectionV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"resure"];
    
    
    self.collectionV.contentSize = CGSizeMake(WIDTH * 9, 0);
    self.collectionV.pagingEnabled = YES;
    self.collectionV.bounces = NO;
    self.collectionV.showsHorizontalScrollIndicator =NO;
    
    self.aview = [[UIView alloc]initWithFrame:CGRectMake(WIDTH/5 , 64, WIDTH/5, 2)];
    
    self.aview.backgroundColor = [UIColor blueColor];
    [self.navigationController.view addSubview:self.aview];
    
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
 
   self.array1 = [NSMutableArray array];
    // Do any additional setup after loading the view.
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.array.count;

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"resure" forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor clearColor];
   
     self.nextPage = 1;

    self.tableV =  [[BaseUITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 22 - 49 - 55) style:UITableViewStylePlain];
        self.tableV.frame = CGRectMake(0, 57, WIDTH, HEIGHT);
        [cell addSubview:self.tableV];
        self.tableV.delegate = self;
        self.tableV.dataSource = self;
    self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.array2 = [NSMutableArray array];
    self.num =indexPath.row;
    [self getInFo];
    

        if (indexPath.item == 0) {
            MyScrollView *scroll = [[MyScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
            scroll.myDelegate = self;
            scroll.backgroundColor = [UIColor whiteColor];
            self.tableV.tableHeaderView=scroll;

            AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
            NSString *url_string = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?cid=6&limit=5&order=-sort_order&_eva_t=1437035429"];
            
            AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
            [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [netWorkManager stopMonitoring];
                self.array3 = [NSMutableArray arrayWithArray:[responseObject objectForKey:@"results"]];
                
             [scroll setImages:self.array3];
            
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
             
                
                [scroll setImages:self.array3];
                
            }];
     
                }
    
    if (indexPath.row < 5) {
        self.scroV.contentOffset = CGPointMake(0, 0);
        [self.aview removeFromSuperview];
        self.aview = [[UIView alloc]initWithFrame:CGRectMake(WIDTH/5 * indexPath.item, 64, WIDTH/5, 2)];
        
        self.aview.backgroundColor = [UIColor blueColor];
        [self.navigationController.view addSubview:self.aview];

    }else{
        self.scroV.contentOffset = CGPointMake(WIDTH, 0);
        [self.aview removeFromSuperview];
        self.aview = [[UIView alloc]initWithFrame:CGRectMake(WIDTH/5 * (indexPath.item - 4), 64, WIDTH/5, 2)];
        
        self.aview.backgroundColor = [UIColor blueColor];
        [self.navigationController.view addSubview:self.aview];
    }
    self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.MBHUD.labelText = @"正在加载中";
    [self.MBHUD show:YES];
    [self.tableV.header beginRefreshing];
    [self headerRefesh];
    [self footerRefesh];

   
    return cell;
}
//-(void)reloadValue {
//    self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    self.MBHUD.labelText = @"正在加载中...";
//    [self.MBHUD show:YES];
//    [self getInFo];
//    
//}

//下拉刷新
-(void)headerRefesh {
    self.tableV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.nextPage = 1;
        self.downUpdata = YES;
        
        //让菊花旋转起来
        self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.MBHUD.labelText = @"正在加载中...";
        [self.MBHUD show:YES];
        [self getInFo];
        
        // 刷新表格
       
        [self.tableV reloadData];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        
        
        
    }];
    
}
#warning 上拉加载
-(void)footerRefesh {
    
    self.tableV.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        
        self.nextPage++;
        self.downUpdata = NO;
        self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.MBHUD.labelText = @"正在加载中...";
        [self.MBHUD show:YES];
        [self getInFo];
        
        // 刷新表格
        [self.tableV reloadData];
        
    }];
    
}



-(void)getInFo{

    if (self.nextPage == 1) {
        self.array2 = [[NewDataBase sharDataBase]selectAllNews];
    }
    
    NSString *url1 = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?type=news,ruanwen&page=%ld&_eva_t=1437035422",self.nextPage];
     NSString *url2 = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?alias=hotNews&page=%ld&_eva_t=1437036939",self.nextPage];
     NSString *url3 = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?cid=16&page=%ld&_eva_t=1437037016",self.nextPage];
     NSString *url4 = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?cid=17&page=%ld&_eva_t=1437037099",self.nextPage];
     NSString *url5 = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?cid=15&page=%ld&_eva_t=1437037122",self.nextPage];
     NSString *url6 = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?cid=19&page=%ld&_eva_t=1437037146",self.nextPage];
     NSString *url7 = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?cid=21&page=%ld&_eva_t=1437037173",self.nextPage];
     NSString *url8 = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?cid=20&page=%ld&_eva_t=1437037214",self.nextPage];
     NSString *url9 = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?cid=22&page=%ld&_eva_t=1437037245",self.nextPage];
    
    NSMutableArray *array = [NSMutableArray arrayWithObjects:url1,url2,url3,url4,url5,url6,url7,url8,url9,nil];
    
    NSString *url_string = [array objectAtIndex:self.num];
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    //    NSString *url_string = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/posts?cid=6&limit=5&order=-sort_order&_eva_t=1437035429"];
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
       
        //如果是下拉
        if (self.nextPage == 1) {
            [self.array2 removeAllObjects];
            [[NewDataBase sharDataBase]dropTable];
            [[NewDataBase sharDataBase]creatTable];
        }
 
        NSMutableArray *array = [NSMutableArray arrayWithArray:[responseObject objectForKey:@"results"]];
        for (NSMutableDictionary *dic in array) {
            NewModel *Newmodel = [[NewModel alloc]init];
            Newmodel.ID = [dic objectForKey:@"id"];
            Newmodel.title = [dic objectForKey:@"title"];
            Newmodel.type = [dic objectForKey:@"type"];
            Newmodel.summary = [dic objectForKey:@"summary"];
            Newmodel.count = [dic objectForKey:@"count"];
            Newmodel.url = [dic objectForKey:@"url"];
            Newmodel.imageUrl = [dic objectForKey:@"imageUrl"];
            
            if (self.nextPage == 1) {
                
                [[NewDataBase sharDataBase]insertNewModel:Newmodel];
            }
            
            [self.array2 addObject:Newmodel];
         
        }
           [self.tableV reloadData];
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tableV.footer endRefreshing];
        [self.tableV.header endRefreshing];
        [self.MBHUD hide:YES];

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
      
                // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tableV.footer endRefreshing];
        [self.tableV.header endRefreshing];
        [self.MBHUD hide:YES];
        UIAlertView *alView = [[UIAlertView alloc]initWithTitle:@"网络不给力" message:@"确认您已连接到网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alView show];
        

        
    }];

}
-(void)bringtapNum:(NSInteger)num{
   
    NSMutableDictionary *dic = [self.array3 objectAtIndex:num];
    NewDetailViewController *newDVC = [[NewDetailViewController alloc]init];
    newDVC.ID = [dic objectForKey:@"id"];
    [self.navigationController pushViewController:newDVC animated:YES];
    
    

}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

  
    
    return self.array2.count;

    
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *indent = @"cell";
    
    NewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indent];
    if (cell == nil) {
        cell = [[NewTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indent];
    }
    cell.backgroundColor = [UIColor clearColor];
   
    NewModel *mewModel =  [self.array2 objectAtIndex:indexPath.row];
    cell.model = mewModel;
    
    
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NewDetailViewController *newDtailVC = [[NewDetailViewController alloc]init];
    [self.navigationController pushViewController:newDtailVC animated:YES];
    NewModel *mewModel =  [self.array2 objectAtIndex:indexPath.row];
    newDtailVC.ID = mewModel.ID;
}



-(void)buttonAction:(UIButton *)button{
    self.collectionV.contentOffset = CGPointMake(button.tag * WIDTH, 0);
    
}
-(void)timeAction{

 [self.aview removeFromSuperview];

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
